import React, { useState, useRef, useEffect } from 'react';
import OpenAI from 'openai';
import SearchControlPanel from '../../components/SearchControlPanel';
import '../../components/SearchControlPanel.css';
import './BinarySearchPlayground.css';

// 配置阿里云百炼AI
const openai = new OpenAI({
  apiKey: 'sk-e50e6d73580e411ca5bbebdda74eedcf',
  baseURL: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
  dangerouslyAllowBrowser: true
});

const BinarySearchPlayground = () => {
  // 面板状态
  const [leftPanelWidth, setLeftPanelWidth] = useState(350);
  const [activeTab, setActiveTab] = useState('settings');
  const [isResizing, setIsResizing] = useState(false);

  // 基础状态
  const [data, setData] = useState([]);
  const [dataSize, setDataSize] = useState(10);
  const [customData, setCustomData] = useState('');
  const [dataMode, setDataMode] = useState('random');
  const [dataError, setDataError] = useState('');

  // 搜索相关状态
  const [target, setTarget] = useState('');
  const [targetError, setTargetError] = useState('');

  // 动画控制
  const [animationSpeed, setAnimationSpeed] = useState(800);
  const [isRunning, setIsRunning] = useState(false);
  const [isPaused, setIsPaused] = useState(false);
  const [isStepping, setIsStepping] = useState(false);
  const [currentStep, setCurrentStep] = useState(0);
  const [totalSteps, setTotalSteps] = useState(0);
  const [status, setStatus] = useState('就绪');

  // AI聊天相关
  const [chatMessages, setChatMessages] = useState([]);
  const [chatInput, setChatInput] = useState('');
  const [isAIResponding, setIsAIResponding] = useState(false);

  // AI对话历史（用于维护上下文）
  const [aiChatHistory, setAiChatHistory] = useState([]);
  
  // 引用
  const dataDisplayRef = useRef(null);
  const barsRef = useRef([]);
  const animationTimeouts = useRef([]);
  const dataRef = useRef([]);
  const runningStateRef = useRef({
    isRunning: false,
    isPaused: false,
    isStepping: false
  });
  
  // 搜索状态
  const searchState = useRef({
    left: 0,
    right: 0,
    mid: 0,
    target: 0,
    found: false,
    phase: 'idle' // idle, searching, found, not-found
  });
  
  // 建议问题状态
  const [suggestedQuestions, setSuggestedQuestions] = useState([
    "生成一组二分查找测试用例",
    "用Java语言实现二分查找",
    "二分查找的时间复杂度是多少？",
    "为什么二分查找需要有序数组？",
    "二分查找的最坏情况是什么？"
  ]);
  
  // 清除所有定时器
  const clearAllTimeouts = () => {
    animationTimeouts.current.forEach(timeout => clearTimeout(timeout));
    animationTimeouts.current = [];
  };
  
  // 停止搜索
  const stopSearch = () => {
    clearAllTimeouts();
    runningStateRef.current.isRunning = false;
    runningStateRef.current.isPaused = false;
    runningStateRef.current.isStepping = false;

    setIsRunning(false);
    setIsPaused(false);
    setIsStepping(false);
    resetSearchState();
    renderData(dataRef.current);
    setStatus('已停止');
  };
  
  // 暂停搜索
  const pauseSearch = () => {
    if (!isRunning || isPaused) return;

    runningStateRef.current.isPaused = true;
    setIsPaused(true);
    setStatus('已暂停');
  };
  
  // 重置搜索状态
  const resetSearchState = () => {
    searchState.current = {
      left: 0,
      right: 0,
      mid: 0,
      target: 0,
      found: false,
      phase: 'idle'
    };
    setCurrentStep(0);
  };
  
  // 睡眠函数
  const sleep = (ms) => {
    return new Promise(resolve => {
      const timeoutId = setTimeout(resolve, ms);
      animationTimeouts.current.push(timeoutId);
    });
  };
  
  // 渲染数据到DOM
  const renderData = (dataArray) => {
    if (!dataDisplayRef.current) return;

    const container = dataDisplayRef.current;
    container.innerHTML = '';
    barsRef.current = [];

    if (dataArray.length === 0) {
      // 显示空状态
      const emptyState = document.createElement('div');
      emptyState.className = 'empty-state';
      emptyState.innerHTML = '<p>点击"生成数据"开始</p>';
      container.appendChild(emptyState);
      return;
    }

    const maxValue = Math.max(...dataArray);

    // 创建一个包装容器来居中显示条形图
    const barsContainer = document.createElement('div');
    barsContainer.className = 'bars-container';

    dataArray.forEach((value, index) => {
      const bar = document.createElement('div');
      bar.className = 'binary-data-bar';
      bar.style.height = `${(value / maxValue) * 200}px`;

      const valueSpan = document.createElement('span');
      valueSpan.className = 'value';
      valueSpan.textContent = value;
      bar.appendChild(valueSpan);

      const indexSpan = document.createElement('span');
      indexSpan.className = 'index';
      indexSpan.textContent = index;
      bar.appendChild(indexSpan);

      barsContainer.appendChild(bar);
      barsRef.current.push(bar);
    });

    container.appendChild(barsContainer);
  };
  
  // 生成随机数据
  const generateRandomData = () => {
    if (dataSize > 20) {
      alert('数据数量不能超过20个');
      return;
    }
    if (dataSize < 5) {
      alert('数据数量不能少于5个');
      return;
    }

    // 生成有序数组
    const newData = [];
    let current = Math.floor(Math.random() * 10) + 1;
    for (let i = 0; i < dataSize; i++) {
      newData.push(current);
      current += Math.floor(Math.random() * 5) + 1;
    }

    setData(newData);
    dataRef.current = [...newData];
    renderData(newData);
    resetSearchState();
    setStatus('就绪');
  };
  
  // 生成自定义数据
  const generateCustomData = () => {
    if (!customData.trim()) {
      setDataError('请输入数据');
      return false;
    }

    try {
      const newData = customData
        .split(',')
        .map(s => s.trim())
        .filter(s => s !== '')
        .map(s => {
          const num = parseInt(s);
          if (isNaN(num)) {
            throw new Error(`"${s}" 不是有效数字`);
          }
          return num;
        });

      if (newData.length < 3) {
        setDataError('至少需要3个数字');
        return false;
      }
      
      if (newData.length > 20) {
        setDataError('最多支持20个数字');
        return false;
      }
      
      // 检查是否有序
      const sorted = [...newData].sort((a, b) => a - b);
      const isOrdered = newData.every((val, idx) => val === sorted[idx]);
      
      if (!isOrdered) {
        setDataError('二分查找需要有序数组，数据已自动排序');
        newData.sort((a, b) => a - b);
      } else {
        setDataError('');
      }

      setData(newData);
      dataRef.current = [...newData];
      renderData(newData);
      resetSearchState();
      setStatus('就绪');
      return true;
    } catch (error) {
      setDataError(error.message);
      return false;
    }
  };
  
  // 处理生成数据
  const handleGenerateData = () => {
    stopSearch();

    if (dataMode === 'custom' && customData.trim()) {
      generateCustomData();
    } else {
      generateRandomData();
      if (dataMode === 'custom') {
        setCustomData('');
        setDataError('');
      }
    }
  };

  // 处理自定义数据变化
  const handleCustomDataChange = (e) => {
    setCustomData(e.target.value);
    setDataError('');
  };

  // 处理目标值变化
  const handleTargetChange = (e) => {
    setTarget(e.target.value);
    setTargetError('');
  };
  
  // 验证目标值
  const validateTarget = () => {
    if (target === '') {
      setTargetError('请输入目标值');
      return false;
    }
    
    const targetNum = parseInt(target);
    if (isNaN(targetNum)) {
      setTargetError('目标值必须是数字');
      return false;
    }
    
    setTargetError('');
    return true;
  };
  
  // 开始搜索
  const startSearch = () => {
    if (isRunning && !isPaused) return;

    if (data.length === 0) {
      alert('请先生成数据');
      return;
    }

    if (!validateTarget()) {
      return;
    }

    if (isPaused) {
      // 如果是暂停状态，则恢复
      runningStateRef.current.isPaused = false;
      setIsPaused(false);
      setStatus('搜索中...');

      // 继续执行搜索步骤
      const timeoutId = setTimeout(() => {
        if (!runningStateRef.current.isPaused && runningStateRef.current.isRunning) {
          runSearchStep();
        }
      }, animationSpeed / 2);
      animationTimeouts.current.push(timeoutId);
      return;
    }

    // 重置状态
    stopSearch();
    resetSearchState();

    // 设置搜索参数
    searchState.current.left = 0;
    searchState.current.right = data.length - 1;
    searchState.current.target = parseInt(target);
    searchState.current.phase = 'searching';

    runningStateRef.current.isRunning = true;
    runningStateRef.current.isPaused = false;
    runningStateRef.current.isStepping = false;

    setIsRunning(true);
    setIsPaused(false);
    setIsStepping(false);
    setCurrentStep(0);
    setTotalSteps(Math.ceil(Math.log2(data.length)) + 1);
    setStatus('开始搜索...');

    // 开始执行搜索
    runSearchStep();
  };

  // 单步执行
  const stepSearch = () => {
    if (isRunning && !isPaused && !isStepping) return;

    if (!isRunning) {
      // 如果没有在运行，开始搜索但设置为单步模式
      if (data.length === 0) {
        alert('请先生成数据');
        return;
      }

      if (!validateTarget()) {
        return;
      }

      // 重置状态
      resetSearchState();

      // 设置搜索参数
      searchState.current.left = 0;
      searchState.current.right = data.length - 1;
      searchState.current.target = parseInt(target);
      searchState.current.phase = 'searching';

      runningStateRef.current.isRunning = true;
      runningStateRef.current.isPaused = true;
      runningStateRef.current.isStepping = true;

      setIsRunning(true);
      setIsPaused(true);
      setIsStepping(true);
      setCurrentStep(0);
      setTotalSteps(Math.ceil(Math.log2(data.length)) + 1);
      setStatus('单步模式 - 点击继续下一步');
    }

    if (isPaused) {
      runningStateRef.current.isPaused = false;
      setIsPaused(false);
      runSearchStep();
    }
  };
  
  // 执行搜索步骤
  const runSearchStep = async () => {
    // 检查是否应该停止
    if (!runningStateRef.current.isRunning) {
      return;
    }

    const { left, right, target, phase } = searchState.current;

    if (phase === 'searching') {
      if (left > right) {
        // 未找到目标值
        searchState.current.phase = 'not-found';
        setStatus(`未找到目标值 ${target}`);

        // 清除所有高亮
        barsRef.current.forEach(bar => {
          if (bar) {
            bar.classList.remove('left-bound', 'right-bound', 'mid-point', 'target-found');
          }
        });

        completeSearch();
        return;
      }

      // 计算中点
      const mid = Math.floor((left + right) / 2);
      searchState.current.mid = mid;

      setCurrentStep(prev => prev + 1);
      setStatus(`比较中点 ${mid} 位置的值 ${dataRef.current[mid]} 与目标值 ${target}`);

      // 清除之前的高亮
      barsRef.current.forEach(bar => {
        if (bar) {
          bar.classList.remove('left-bound', 'right-bound', 'mid-point', 'target-found');
        }
      });

      // 高亮当前搜索范围
      if (barsRef.current[left]) {
        barsRef.current[left].classList.add('left-bound');
      }
      if (barsRef.current[right]) {
        barsRef.current[right].classList.add('right-bound');
      }
      if (barsRef.current[mid]) {
        barsRef.current[mid].classList.add('mid-point');
      }

      await sleep(animationSpeed);

      if (!runningStateRef.current.isRunning) return;

      // 比较中点值与目标值
      const midValue = dataRef.current[mid];

      if (midValue === target) {
        // 找到目标值
        searchState.current.found = true;
        searchState.current.phase = 'found';

        if (barsRef.current[mid]) {
          barsRef.current[mid].classList.remove('mid-point');
          barsRef.current[mid].classList.add('target-found');
        }

        setStatus(`找到目标值 ${target} 在位置 ${mid}`);

        completeSearch();
        return;
      } else if (midValue < target) {
        // 目标值在右半部分
        searchState.current.left = mid + 1;
        setStatus(`${midValue} < ${target}，搜索右半部分`);
      } else {
        // 目标值在左半部分
        searchState.current.right = mid - 1;
        setStatus(`${midValue} > ${target}，搜索左半部分`);
      }

      if (runningStateRef.current.isStepping) {
        runningStateRef.current.isPaused = true;
        setIsPaused(true);
        setStatus(prev => prev + ' - 等待下一步');
        return;
      }

      // 继续下一步
      const timeoutId = setTimeout(() => {
        if (!runningStateRef.current.isPaused && runningStateRef.current.isRunning) {
          runSearchStep();
        }
      }, animationSpeed / 2);
      animationTimeouts.current.push(timeoutId);
    }
  };

  // 完成搜索
  const completeSearch = () => {
    runningStateRef.current.isRunning = false;
    runningStateRef.current.isPaused = false;
    runningStateRef.current.isStepping = false;

    setIsRunning(false);
    setIsPaused(false);
    setIsStepping(false);

    const { found, target } = searchState.current;
    if (found) {
      setStatus(`搜索完成！找到目标值 ${target}`);
    } else {
      setStatus(`搜索完成！未找到目标值 ${target}`);
    }
  };

  // 真实AI调用函数
  const getAIResponse = async (userMessages) => {
    try {
      // 构建完整的消息数组，包含系统提示词
      const systemPrompt = {
        role: "system",
        content: `# 角色
你是一位专业的AI辅助，擅长处理基础算法和数据结构问题，并能够根据用户的需求生成相应的测试数据或解答疑惑。

## 结构化回复模板
{
    "status": <0或1>,
    "data": <指定数据，通常用数组格式，可为null>,
    "message": <回复的内容，字符串>,
    "associate1" : <通过对方的提问以及回答，联想的问题1>,
    "associate2" : <通过对方的提问以及回答，联想的问题2>,
    "associate3" : <通过对方的提问以及回答，联想的问题3>
}

## 技能

### 技能1：答案识别与回应
- **任务**：根据用户发来的信息，通过合理判断，返回一个JSON格式的数据。且对应JSON字段里的\`status\`值，只有两种可能性。
  - 如果用户发来的信息包含但不限于"生成"、"测试数据"等关键字，\`status\`为1，同时\`data\`字段为生成的有序数组数据，且\`message\`字段为几乎固定的回复。生成的每个联想问题最好不超过15字。例如：
    {
        "status": 1,
        "data": [1, 3, 5, 7, 9, 11, 13, 15],
        "message": "已生成符合你要求的有序数据！",
        "associate1" :  "有没有最坏情况的数据",
        "associate2" :  "这个数据的查找效率如何",
        "associate3" :  "有没有办法进一步优化算法"
    }
  - 如果通过你的判断，用户的提问是为了解答疑惑，而非生成测试样例，那么\`status\`为0，\`data\`为null，且正常生成回复。例如：
    {
        "status": 0,
        "data": null,
        "message": "二分查找通过比较中间元素与目标值，将搜索范围缩小一半",
        "associate1" : "为什么需要有序数组",
        "associate2" : "时间复杂度是多少",
        "associate3" : "最坏情况是什么"
    }

## 限制

- 每次回复的内容必须是一个结构化数据（JSON格式），不能有其他任何多余的文字。
- 包括接下来括号里的东西，也不要在回复中出现！！这非常重要，否则会影响网页的渲染。右边括号内的内容不允许出现('''json)
- 如果message字段中包含代码，必须使用标准的Markdown代码块格式：三个反引号+语言名+换行+代码内容+换行+三个反引号
- 代码块必须指定正确的语言标识符，如：java、python、c、javascript等
- 生成的测试数据必须是有序数组，适合二分查找算法

`
      };

      const messages = [systemPrompt, ...userMessages];

      const completion = await openai.chat.completions.create({
        model: "qwen-plus",
        messages: messages,
      });
      return completion.choices[0].message.content;
    } catch (error) {
      console.error("Error fetching AI response:", error);
      throw error;
    }
  };

  const handleSendMessage = async (message) => {
    if (!message.trim() || isAIResponding) return;

    // 添加用户消息
    const userMessage = {
      id: Date.now(),
      type: 'user',
      content: message,
      timestamp: new Date()
    };

    setChatMessages(prev => [...prev, userMessage]);
    setChatInput('');
    setIsAIResponding(true);

    try {
      // 构建对话历史
      const newChatHistory = [
        ...aiChatHistory,
        { role: "user", content: message }
      ];

      // 调用真实AI
      const aiResponseText = await getAIResponse(newChatHistory);

      // 调试：输出AI原始回复
      console.log('=== AI原始回复 ===');
      console.log('内容:', aiResponseText);

      // 解析AI回复的JSON
      let aiResponse;
      try {
        aiResponse = JSON.parse(aiResponseText);
        console.log('=== JSON解析成功 ===');
        console.log('解析后的对象:', aiResponse);
      } catch (parseError) {
        console.log('=== JSON解析失败 ===');
        console.log('解析错误:', parseError.message);
        // 如果不是JSON格式，当作普通回复处理
        aiResponse = {
          status: 0,
          data: null,
          message: aiResponseText,
          associate1: null,
          associate2: null,
          associate3: null
        };
      }

      // 处理AI回复
      const aiMessage = {
        id: Date.now() + 1,
        type: 'ai',
        content: aiResponse.message,
        timestamp: new Date()
      };

      setChatMessages(prev => [...prev, aiMessage]);

      // 更新建议问题
      if (aiResponse.associate1 || aiResponse.associate2 || aiResponse.associate3) {
        const newSuggestions = [
          aiResponse.associate1,
          aiResponse.associate2,
          aiResponse.associate3
        ].filter(q => q && q.trim()); // 过滤掉空值

        if (newSuggestions.length > 0) {
          setSuggestedQuestions(newSuggestions);
        }
      }

      // 如果status为1，说明AI生成了数据，需要应用到参数设置
      if (aiResponse.status === 1 && aiResponse.data && Array.isArray(aiResponse.data)) {
        console.log('生成的数据:', aiResponse.data);

        // 切换到参数设置标签
        setActiveTab('settings');

        // 设置为自定义数据模式
        setDataMode('custom');

        // 填入AI生成的数据
        const dataString = aiResponse.data.join(', ');
        setCustomData(dataString);

        // 清除错误信息
        setDataError('');
      }

      // 更新对话历史
      setAiChatHistory([
        ...newChatHistory,
        { role: "assistant", content: aiResponseText }
      ]);

    } catch (error) {
      console.error("获取AI回复失败:", error);
      const errorMessage = {
        id: Date.now() + 1,
        type: 'ai',
        content: "抱歉，我暂时无法回复。请稍后再试。",
        timestamp: new Date()
      };
      setChatMessages(prev => [...prev, errorMessage]);
    } finally {
      setIsAIResponding(false);
    }
  };

  // 处理建议问题点击
  const handleSuggestedQuestionClick = (question) => {
    setChatInput(question);
    handleSendMessage(question);
  };

  // 拖拽处理函数
  const handleMouseDown = (e) => {
    setIsResizing(true);
    e.preventDefault();
  };

  const handleMouseMove = (e) => {
    if (!isResizing) return;

    const newWidth = e.clientX - 20; // 减去容器的padding
    if (newWidth >= 300 && newWidth <= 1000) {
      setLeftPanelWidth(newWidth);
    }
  };

  const handleMouseUp = () => {
    setIsResizing(false);
  };

  // 添加全局鼠标事件监听
  useEffect(() => {
    if (isResizing) {
      document.addEventListener('mousemove', handleMouseMove);
      document.addEventListener('mouseup', handleMouseUp);
      document.body.style.cursor = 'col-resize';
      document.body.style.userSelect = 'none';
    } else {
      document.removeEventListener('mousemove', handleMouseMove);
      document.removeEventListener('mouseup', handleMouseUp);
      document.body.style.cursor = '';
      document.body.style.userSelect = '';
    }

    return () => {
      document.removeEventListener('mousemove', handleMouseMove);
      document.removeEventListener('mouseup', handleMouseUp);
      document.body.style.cursor = '';
      document.body.style.userSelect = '';
    };
  }, [isResizing]);

  // 初始化
  useEffect(() => {
    generateRandomData();

    return () => {
      clearAllTimeouts();
    };
  }, []);
  
  return (
    <div className="binary-search-playground">
      <div className="binary-search-container">
        {/* 左侧控制面板 */}
        <div
          className="left-panel"
          style={{ width: `${leftPanelWidth}px` }}
        >
          <SearchControlPanel
            // 面板状态
            leftPanelWidth={leftPanelWidth}
            activeTab={activeTab}
            setActiveTab={setActiveTab}

            // 数据相关
            data={data}
            dataMode={dataMode}
            setDataMode={setDataMode}
            customData={customData}
            setCustomData={setCustomData}
            dataError={dataError}
            dataSize={dataSize}
            setDataSize={setDataSize}
            handleGenerateData={handleGenerateData}
            handleCustomDataChange={handleCustomDataChange}

            // 搜索设置
            target={target}
            setTarget={setTarget}
            targetError={targetError}
            handleTargetChange={handleTargetChange}

            // 动画控制
            animationSpeed={animationSpeed}
            setAnimationSpeed={setAnimationSpeed}

            // 搜索控制
            isRunning={isRunning}
            isPaused={isPaused}
            isStepping={isStepping}
            startSearch={startSearch}
            stepSearch={stepSearch}
            pauseSearch={pauseSearch}
            stopSearch={stopSearch}

            // 状态信息
            status={status}
            currentStep={currentStep}
            totalSteps={totalSteps}

            // AI聊天
            chatMessages={chatMessages}
            chatInput={chatInput}
            setChatInput={setChatInput}
            isAIResponding={isAIResponding}
            handleSendMessage={handleSendMessage}
            suggestedQuestions={suggestedQuestions}
            handleSuggestedQuestionClick={handleSuggestedQuestionClick}

            // 算法名称
            algorithmName="二分查找"
          />
        </div>

        {/* 拖拽分隔条 */}
        <div
          className="resize-handle"
          onMouseDown={handleMouseDown}
        ></div>

        {/* 右侧动画面板 */}
        <div className="animation-panel">
          <h2>动画展示</h2>
          <div className="data-visualization" ref={dataDisplayRef}>
            {/* 数据条形图将在这里渲染 */}
          </div>
        </div>
      </div>
    </div>
  );
};

export default BinarySearchPlayground;
